package com.hxalex.simulationhandle.ui.task;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.hxalex.simulationhandle.R;
import com.hxalex.simulationhandle.accessbilityService.HandleService;
import com.hxalex.simulationhandle.accessbilityService.manger.CommandManger;
import com.hxalex.simulationhandle.accessbilityService.manger.SearchManger;
import com.hxalex.simulationhandle.accessbilityService.manger.WifiManger;
import com.hxalex.simulationhandle.databinding.ActivityDetailTaskBinding;
import com.hxalex.simulationhandle.ui.base.BaseActivity;
import com.hxalex.simulationhandle.ui.home.model.KeyWordBean;
import com.hxalex.simulationhandle.ui.home.model.TaskBean;
import com.hxalex.simulationhandle.ui.home.model.WebSiteBean;
import com.hxalex.simulationhandle.ui.home.presenter.TaskPersenter;
import com.hxalex.simulationhandle.ui.permission.manger.PermissionManger;
import com.hxalex.simulationhandle.util.AppAvilbleUtils;
import com.leon.lfilepickerlibrary.LFilePicker;

import java.util.ArrayList;
import java.util.List;

public class DetailTaskActivity extends BaseActivity implements View.OnClickListener {
    private static final int REQUESTCODE_FROM_ACTIVITY_KEYWORD_UPDATE=1002;
    private static final int REQUESTCODE_FROM_ACTIVITY_WEBSITE_UPDATE=1003;
    private ActivityDetailTaskBinding mBinding;
    private TaskBean taskBean;
    private TaskPersenter mPresenter;
    private    List<WebSiteBean> webSiteBeans;
    private List<KeyWordBean> taskKeyWords ;
    private boolean isEdit=false;//是否打开编辑
    private boolean isUpdateKeyword;
    private boolean isUpdateWebSite;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_detail_task);
        initToolBarWithRightMenu("编辑",v -> 
        {
           editContronl();
        });
        taskBean= (TaskBean) getIntent().getSerializableExtra(TaskPersenter.DETAIL_TASK);
        initView();
    }

    private void initView() {
        mPresenter=new TaskPersenter(this);
        mBinding.txtTaskTitle.setText(taskBean.getTaskTitle());
        mBinding.txtExecute.setText(taskBean.getTaskExecuteNum()+"");
        mBinding.txtStopTime.setText(taskBean.getTaskStopTime()+"");
        webSiteBeans = mPresenter.getWebSiteWords(taskBean);
        taskKeyWords = mPresenter.getTaskKeyWords(taskBean);
        for(WebSiteBean s:webSiteBeans)
        {
            Log.e("webSiteBeans",s.getWebSiteString());
        }

        for(KeyWordBean s:taskKeyWords)
        {
            Log.e("taskKeyWords",s.getKeyWordString());
        }
        
        
        mBinding.txtKeywordHint.setHint(taskKeyWords.size()+"个关键词");
        mBinding.txtWebsiteHint.setHint(webSiteBeans.size()+"个网站库词");
        mBinding.btnAddKeyWord.setEnabled(false);
        mBinding.btnAddWebSite.setEnabled(false);
        mBinding.btnAddKeyWord.setOnClickListener(v->
        {
            
            openFileList(REQUESTCODE_FROM_ACTIVITY_KEYWORD_UPDATE);
        });
        mBinding.btnAddWebSite.setOnClickListener(v->
        {
            openFileList(REQUESTCODE_FROM_ACTIVITY_WEBSITE_UPDATE);
        });
     mBinding.btnStartTask.setOnClickListener(this);
    }



    @Override
    public void onClick(View v) {
        //检查权限是否全部开启
        boolean isHaveAllPermission=PermissionManger.getManger(this).isHaveAllPermission;
        boolean isAvilbleWifi=   AppAvilbleUtils.isAvilible(this,getResources().getString(R.string.wifi_app_package_name));
        if(!isHaveAllPermission || !isAvilbleWifi)
        {
            Toast.makeText(this,"您有权限尚未打开或为安装wifi万能钥匙，无法开始执行任务。请检查！",Toast.LENGTH_LONG).show();
            return;
        }
        //重置管理类
        WifiManger.ClearManger();
        SearchManger.ClearManger();
        WifiManger wifiManger = WifiManger.getWifiManger(this);
        SearchManger searchManger = SearchManger.getSearchManger(this);
        //注入当前任务的相关信息进入搜索管理类
        searchManger.setKeyWordData(taskKeyWords);
        searchManger.setWebSiteData(webSiteBeans);
        searchManger.setWebSiteStopTime(taskBean.getTaskStopTime());
        searchManger.setTaskLoopNum(taskBean.getTaskExecuteNum());
        searchManger.setNowTaskLoopNum(1);
        //WiFi任务开始执行
        //加载一系列命令时，先清空所有命令
        CommandManger.getManger().getCommandQueue().clear();
        wifiManger.openWifiHelper();
        wifiManger.loadAllWifiCommand();
        HandleService.isStartService=true;
    }

    private void openFileList(int code)
    {
        new LFilePicker().withActivity(this)
                .withRequestCode(code)
                .withStartPath("/storage/emulated/0")
                .withIsGreater(false)
                .withFileSize(500 * 1024)
                .withFileFilter(new String[]{".txt"})
                .withMutilyMode(false)
                .withBackgroundColor("#2BD491")
                .start();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUESTCODE_FROM_ACTIVITY_KEYWORD_UPDATE|| requestCode ==REQUESTCODE_FROM_ACTIVITY_WEBSITE_UPDATE) {
                ArrayList<String> path =data.getStringArrayListExtra("paths");
                Log.i("msg", path.get(0)+"   size:"+path.size());
                if(path.size()<0) return;
                if(requestCode == REQUESTCODE_FROM_ACTIVITY_KEYWORD_UPDATE) 
                {
                    updatekeyWord(path.get(0));
                    isUpdateKeyword=true;
                }
                if(requestCode == REQUESTCODE_FROM_ACTIVITY_WEBSITE_UPDATE)
                {
                    updateWebSite(path.get(0));
                    isUpdateWebSite=true;
                }
            }
        }
    }


    private void updatekeyWord(String path)
    {
        List<String> strings = mPresenter.parseKeyWordFile(path);
        taskKeyWords=new ArrayList<>();
        for(String s:strings)
        {
            taskKeyWords.add(new KeyWordBean(s));
        }

        if(taskKeyWords.size()>0)
        {
            Toast.makeText(this,"网站库解析完成，总共"+taskKeyWords.size()+"个网站库词",Toast.LENGTH_LONG).show();
            mBinding.txtKeywordHint.setHint(taskKeyWords.size()+"个关键词");
            taskBean.setTaskKeyWord(taskKeyWords.size());
      
        }

        for(KeyWordBean b:taskKeyWords) Log.i("msg",b.getKeyWordString() );

    }

    private void updateWebSite(String path)
    {
        List<String> strings = mPresenter.parseKeyWordFile(path);
        webSiteBeans=new ArrayList<>();
        for(String s:strings)
        {
            webSiteBeans.add(new WebSiteBean(s));
        }

        if(webSiteBeans.size()>0)
        {
            Toast.makeText(this,"网站库解析完成，总共"+webSiteBeans.size()+"个网站库词",Toast.LENGTH_LONG).show();
            mBinding.txtWebsiteHint.setHint(webSiteBeans.size()+"个网站库词");
            taskBean.setTaskWebSite(webSiteBeans.size());
        }

        for(WebSiteBean b:webSiteBeans) Log.i("msg",b.getWebSiteString() );
    }

    private void editContronl()
    {
        Button btn = findViewById(R.id.btn_toolbar_right);
        if(!isEdit)
        {
            isEdit=true;
            btn.setText("完成编辑");
            mBinding.txtTaskTitle.setEnabled(true);
            mBinding.txtExecute.setEnabled(true);
            mBinding.txtStopTime.setEnabled(true);
            mBinding.btnAddKeyWord.setEnabled(true);
            mBinding.btnAddWebSite.setEnabled(true);
            
        }else if(isEdit)
        {
            isEdit=false;
            updateTask();
            mPresenter.updateTaskInfo(taskBean,taskKeyWords,webSiteBeans,isUpdateKeyword,isUpdateWebSite);
            TaskBean taskInfo = mPresenter.getTaskInfo(taskBean);
            taskBean=taskInfo;
            mBinding.txtTaskTitle.setText(taskBean.getTaskTitle());
            mBinding.txtExecute.setText(taskBean.getTaskExecuteNum()+"");
            mBinding.txtStopTime.setText(taskBean.getTaskStopTime()+"");
            mBinding.txtKeywordHint.setHint(taskKeyWords.size()+"个关键词");
            mBinding.txtWebsiteHint.setHint(webSiteBeans.size()+"个网站库词");
            btn.setText("编辑");
            mBinding.txtTaskTitle.setEnabled(false);
            mBinding.txtExecute.setEnabled(false);
            mBinding.txtStopTime.setEnabled(false);
            mBinding.btnAddKeyWord.setEnabled(false);
            mBinding.btnAddWebSite.setEnabled(false);
        }
        
    }
    
    public void updateTask()
    {
        String errormsg="";
        String txtTaskTitle = mBinding.txtTaskTitle.getText().toString();
        String txtExecute = mBinding.txtExecute.getText().toString();
        String txStopTime = mBinding.txtExecute.getText().toString();
        if(txtTaskTitle.equals("") || txtTaskTitle==null) errormsg="标题不能为空";
        if(txtExecute.equals("") || txtExecute==null) errormsg="执行次数不能为空";
        if(txStopTime.equals("") || txStopTime==null) errormsg="页面停留时间不能为空";
        if(!errormsg.equals(""))
        {
            Toast.makeText(this,errormsg,Toast.LENGTH_SHORT).show();
            return;
        }
        taskBean.setTaskTitle(txtTaskTitle);
        taskBean.setTaskExecuteNum(Integer.valueOf(txtExecute));
        taskBean.setTaskStopTime(Integer.valueOf(txStopTime));
    }

    
}
